<!-- 省市选择弹窗组件 -->
<template>
  <nut-popup :visible="visible" position="bottom" round :close-on-click-overlay="true" @close="handleClose" @update:visible="(value: boolean) => emit('update:visible', value)">
    <view class="bg-white rounded-t-3xl overflow-hidden max-h-[80vh] flex flex-col">
      <!-- 标题栏 -->
      <view class="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-white sticky top-0 z-10">
        <view class="text-[32rpx] font-semibold text-gray-900">{{ title }}</view>
        <view class="w-[48rpx] h-[48rpx] flex items-center justify-center rounded-full bg-gray-100 text-gray-500 cursor-pointer transition-colors duration-200 active:bg-gray-200" @click="handleClose">
          <IconFont name="close" size="32rpx" />
        </view>
      </view>

      <!-- 选择器内容 -->
      <view class="flex-1 flex overflow-hidden">
        <!-- 省份选择 -->
        <view class="flex-1 flex flex-col min-w-0 border-r border-gray-100">
          <view class="px-6 py-3 text-[24rpx] text-gray-500 bg-gray-50 border-b border-gray-100 sticky top-0 z-5"> 选择省份 </view>
          <scroll-view class="flex-1 overflow-y-auto max-h-[60vh]" scroll-y>
            <view
              v-for="province in provinceList"
              :key="province.code"
              class="flex items-center justify-between px-6 py-1 border-b border-gray-50 cursor-pointer transition-all duration-200 min-h-[88rpx] active:bg-blue-50"
              :class="{ 'bg-blue-50 border-blue-200': selectedProvince?.code === province.code }"
              @click="selectProvince(province)"
            >
              <text class="text-[28rpx] text-gray-700 flex-1" :class="{ 'text-blue-600 font-medium': selectedProvince?.code === province.code }">
                {{ province.name }}
              </text>
              <IconFont v-if="selectedProvince?.code === province.code" name="check" size="32rpx" class="text-blue-600 ml-4" />
            </view>
          </scroll-view>
        </view>

        <!-- 城市选择 -->
        <view v-if="mode === 'city'" class="flex-1 flex flex-col min-w-0">
          <view class="px-6 py-3 text-[24rpx] text-gray-500 bg-gray-50 border-b border-gray-100 sticky top-0 z-5"> 选择城市 </view>
          
          <!-- 加载状态 -->
          <view v-if="loading" class="flex-1 flex items-center justify-center text-gray-400">
            <view class="text-center">
              <IconFont name="loading" size="48rpx" class="animate-spin mb-4" />
              <text class="text-[28rpx]">正在加载城市数据...</text>
            </view>
          </view>
          
          <!-- 城市列表 -->
          <scroll-view v-else-if="cityList.length > 0" class="flex-1 overflow-y-auto max-h-[60vh]" scroll-y>
            <view
              v-for="city in cityList"
              :key="city.code"
              class="flex items-center justify-between px-6 py-1 border-b border-gray-50 cursor-pointer transition-all duration-200 min-h-[88rpx] active:bg-blue-50"
              :class="{ 'bg-blue-50 border-blue-200': selectedCity?.code === city.code }"
              @click="selectCity(city)"
            >
              <text class="text-[28rpx] text-gray-700 flex-1" :class="{ 'text-blue-600 font-medium': selectedCity?.code === city.code }">
                {{ city.name }}
              </text>
              <IconFont v-if="selectedCity?.code === city.code" name="check" size="32rpx" class="text-blue-600 ml-4" />
            </view>
          </scroll-view>
          
          <!-- 未选择省份时的提示 -->
          <view v-else-if="!selectedProvince" class="flex-1 flex flex-col items-center justify-center text-gray-400">
            <IconFont name="location" size="64rpx" class="mb-4" />
            <text class="text-[28rpx]">请先选择省份</text>
          </view>
        </view>
      </view>

      <!-- 确认按钮 -->
      <view class="p-6 bg-white border-t border-gray-100 sticky bottom-0 z-10">
        <view class="w-full h-[88rpx] bg-blue-600 rounded-2xl flex items-center justify-center cursor-pointer transition-all duration-200 active:bg-blue-700 active:scale-95" @click="handleConfirm">
          <text class="text-[32rpx] font-medium text-white">确认</text>
        </view>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { IconFont } from "@nutui/icons-vue-taro";

/**
 * 省市区数据类型定义
 */
interface RegionData {
  code: string;
  name: string;
  level: number;
  parentCode?: string;
}

/**
 * 选择结果类型定义
 */
interface SelectionResult {
  province?: RegionData;
  city?: RegionData;
}

/**
 * 组件Props类型定义
 */
interface Props {
  /** 是否显示弹窗 */
  visible: boolean;
  /** 选择模式：province-仅选择省份，city-选择省市 */
  mode?: "province" | "city";
  /** 弹窗标题 */
  title?: string;
  /** 默认选中的省份代码 */
  defaultProvinceCode?: string;
  /** 默认选中的城市代码 */
  defaultCityCode?: string;
}

/**
 * 组件Emits类型定义
 */
interface Emits {
  /** 更新visible状态 */
  (e: "update:visible", value: boolean): void;
  /** 选择完成事件 */
  (e: "confirm", result: SelectionResult): void;
  /** 取消选择事件 */
  (e: "cancel"): void;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "province",
  title: "选择服务区域",
  defaultProvinceCode: "",
  defaultCityCode: "",
});

const emit = defineEmits<Emits>();

// 响应式数据
const provinceList = ref<RegionData[]>([]);
const cityList = ref<RegionData[]>([]);
const selectedProvince = ref<RegionData | null>(null);
const selectedCity = ref<RegionData | null>(null);
const loading = ref(false); // 加载状态
const isConfirming = ref(false); // 标志位，用于区分确认关闭和取消关闭

/**
 * 获取省市区数据（仅使用静态数据）
 */
const fetchRegionData = async (parentCode = "0"): Promise<RegionData[]> => {
  try {
    if (parentCode === "0") {
      // 省份数据直接使用静态数据
      return getStaticRegionData(parentCode);
    } else {
      // 城市数据优先从接口获取
      const response = await fetch(`https://datavmap-public.oss-cn-hangzhou.aliyuncs.com/areas/csv/${parentCode}_city.json`);
      if (response.ok) {
        const data = await response.json();
        if (data.rows && Array.isArray(data.rows)) {
          return data.rows.map((item: any) => ({
            code: item.adcode,
            name: item.name,
            level: 2,
            parentCode: parentCode
          }));
        }
      }
      throw new Error('接口请求失败');
    }
  } catch (error) {
    console.warn('从接口获取城市数据失败，使用静态数据:', error);
    // 接口失败时使用静态数据作为备用
    return getStaticRegionData(parentCode);
  }
};

/**
 * 静态省市区数据（主要数据源）
 * 包含全国所有省份和主要城市数据
 * @param parentCode 父级代码
 * @returns 区域数据列表
 */
const getStaticRegionData = (parentCode: string): RegionData[] => {
  if (parentCode === "0") {
    // 省份数据（34个省级行政区）
    return [
      { code: "110000", name: "北京市", level: 1 },
      { code: "120000", name: "天津市", level: 1 },
      { code: "130000", name: "河北省", level: 1 },
      { code: "140000", name: "山西省", level: 1 },
      { code: "150000", name: "内蒙古自治区", level: 1 },
      { code: "210000", name: "辽宁省", level: 1 },
      { code: "220000", name: "吉林省", level: 1 },
      { code: "230000", name: "黑龙江省", level: 1 },
      { code: "310000", name: "上海市", level: 1 },
      { code: "320000", name: "江苏省", level: 1 },
      { code: "330000", name: "浙江省", level: 1 },
      { code: "340000", name: "安徽省", level: 1 },
      { code: "350000", name: "福建省", level: 1 },
      { code: "360000", name: "江西省", level: 1 },
      { code: "370000", name: "山东省", level: 1 },
      { code: "410000", name: "河南省", level: 1 },
      { code: "420000", name: "湖北省", level: 1 },
      { code: "430000", name: "湖南省", level: 1 },
      { code: "440000", name: "广东省", level: 1 },
      { code: "450000", name: "广西壮族自治区", level: 1 },
      { code: "460000", name: "海南省", level: 1 },
      { code: "500000", name: "重庆市", level: 1 },
      { code: "510000", name: "四川省", level: 1 },
      { code: "520000", name: "贵州省", level: 1 },
      { code: "530000", name: "云南省", level: 1 },
      { code: "540000", name: "西藏自治区", level: 1 },
      { code: "610000", name: "陕西省", level: 1 },
      { code: "620000", name: "甘肃省", level: 1 },
      { code: "630000", name: "青海省", level: 1 },
      { code: "640000", name: "宁夏回族自治区", level: 1 },
      { code: "650000", name: "新疆维吾尔自治区", level: 1 },
      { code: "710000", name: "台湾省", level: 1 },
      { code: "810000", name: "香港特别行政区", level: 1 },
      { code: "820000", name: "澳门特别行政区", level: 1 },
    ];
  }

  // 主要城市数据（包含主要省份的城市）
  const cityMap: Record<string, RegionData[]> = {
    "110000": [{ code: "110100", name: "北京市", level: 2, parentCode: "110000" }],
    "120000": [{ code: "120100", name: "天津市", level: 2, parentCode: "120000" }],
    "130000": [
      { code: "130100", name: "石家庄市", level: 2, parentCode: "130000" },
      { code: "130200", name: "唐山市", level: 2, parentCode: "130000" },
      { code: "130300", name: "秦皇岛市", level: 2, parentCode: "130000" },
      { code: "130400", name: "邯郸市", level: 2, parentCode: "130000" },
      { code: "130500", name: "邢台市", level: 2, parentCode: "130000" },
      { code: "130600", name: "保定市", level: 2, parentCode: "130000" },
      { code: "130700", name: "张家口市", level: 2, parentCode: "130000" },
      { code: "130800", name: "承德市", level: 2, parentCode: "130000" },
      { code: "130900", name: "沧州市", level: 2, parentCode: "130000" },
      { code: "131000", name: "廊坊市", level: 2, parentCode: "130000" },
      { code: "131100", name: "衡水市", level: 2, parentCode: "130000" },
    ],
    "310000": [{ code: "310100", name: "上海市", level: 2, parentCode: "310000" }],
    "320000": [
      { code: "320100", name: "南京市", level: 2, parentCode: "320000" },
      { code: "320200", name: "无锡市", level: 2, parentCode: "320000" },
      { code: "320300", name: "徐州市", level: 2, parentCode: "320000" },
      { code: "320400", name: "常州市", level: 2, parentCode: "320000" },
      { code: "320500", name: "苏州市", level: 2, parentCode: "320000" },
      { code: "320600", name: "南通市", level: 2, parentCode: "320000" },
      { code: "320700", name: "连云港市", level: 2, parentCode: "320000" },
      { code: "320800", name: "淮安市", level: 2, parentCode: "320000" },
      { code: "320900", name: "盐城市", level: 2, parentCode: "320000" },
      { code: "321000", name: "扬州市", level: 2, parentCode: "320000" },
      { code: "321100", name: "镇江市", level: 2, parentCode: "320000" },
      { code: "321200", name: "泰州市", level: 2, parentCode: "320000" },
      { code: "321300", name: "宿迁市", level: 2, parentCode: "320000" },
    ],
    "410000": [
      { code: "410100", name: "郑州市", level: 2, parentCode: "410000" },
      { code: "410200", name: "开封市", level: 2, parentCode: "410000" },
      { code: "410300", name: "洛阳市", level: 2, parentCode: "410000" },
      { code: "410400", name: "平顶山市", level: 2, parentCode: "410000" },
      { code: "410500", name: "安阳市", level: 2, parentCode: "410000" },
      { code: "410600", name: "鹤壁市", level: 2, parentCode: "410000" },
      { code: "410700", name: "新乡市", level: 2, parentCode: "410000" },
      { code: "410800", name: "焦作市", level: 2, parentCode: "410000" },
      { code: "410900", name: "濮阳市", level: 2, parentCode: "410000" },
      { code: "411000", name: "许昌市", level: 2, parentCode: "410000" },
      { code: "411100", name: "漯河市", level: 2, parentCode: "410000" },
      { code: "411200", name: "三门峡市", level: 2, parentCode: "410000" },
      { code: "411300", name: "南阳市", level: 2, parentCode: "410000" },
      { code: "411400", name: "商丘市", level: 2, parentCode: "410000" },
      { code: "411500", name: "信阳市", level: 2, parentCode: "410000" },
      { code: "411600", name: "周口市", level: 2, parentCode: "410000" },
      { code: "411700", name: "驻马店市", level: 2, parentCode: "410000" },
      { code: "419001", name: "济源市", level: 2, parentCode: "410000" },
    ],
    "440000": [
      { code: "440100", name: "广州市", level: 2, parentCode: "440000" },
      { code: "440200", name: "韶关市", level: 2, parentCode: "440000" },
      { code: "440300", name: "深圳市", level: 2, parentCode: "440000" },
      { code: "440400", name: "珠海市", level: 2, parentCode: "440000" },
      { code: "440500", name: "汕头市", level: 2, parentCode: "440000" },
      { code: "440600", name: "佛山市", level: 2, parentCode: "440000" },
      { code: "440700", name: "江门市", level: 2, parentCode: "440000" },
      { code: "440800", name: "湛江市", level: 2, parentCode: "440000" },
      { code: "440900", name: "茂名市", level: 2, parentCode: "440000" },
      { code: "441200", name: "肇庆市", level: 2, parentCode: "440000" },
      { code: "441300", name: "惠州市", level: 2, parentCode: "440000" },
      { code: "441400", name: "梅州市", level: 2, parentCode: "440000" },
      { code: "441500", name: "汕尾市", level: 2, parentCode: "440000" },
      { code: "441600", name: "河源市", level: 2, parentCode: "440000" },
      { code: "441700", name: "阳江市", level: 2, parentCode: "440000" },
      { code: "441800", name: "清远市", level: 2, parentCode: "440000" },
      { code: "441900", name: "东莞市", level: 2, parentCode: "440000" },
      { code: "442000", name: "中山市", level: 2, parentCode: "440000" },
      { code: "445100", name: "潮州市", level: 2, parentCode: "440000" },
      { code: "445200", name: "揭阳市", level: 2, parentCode: "440000" },
      { code: "445300", name: "云浮市", level: 2, parentCode: "440000" },
    ],
  };

  return cityMap[parentCode] || [];
};

/**
 * 初始化省份数据
 */
const initProvinceData = async () => {
  loading.value = true;
  try {
    provinceList.value = await fetchRegionData("0");

    // 如果有默认选中的省份，则选中它
    if (props.defaultProvinceCode) {
      const defaultProvince = provinceList.value.find((p) => p.code === props.defaultProvinceCode);
      if (defaultProvince) {
        selectedProvince.value = defaultProvince;

        // 如果是城市模式，加载对应城市数据
        if (props.mode === "city") {
          await loadCityData(props.defaultProvinceCode);
        }
      }
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 加载城市数据
 * @param provinceCode 省份代码
 */
const loadCityData = async (provinceCode: string) => {
  loading.value = true;
  try {
    cityList.value = await fetchRegionData(provinceCode);

    // 如果有默认选中的城市，则选中它
    if (props.defaultCityCode) {
      const defaultCity = cityList.value.find((c) => c.code === props.defaultCityCode);
      if (defaultCity) {
        selectedCity.value = defaultCity;
      }
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 选择省份
 * @param province 选中的省份
 */
const selectProvince = async (province: RegionData) => {
  selectedProvince.value = province;
  selectedCity.value = null; // 重置城市选择

  // 如果是城市模式，加载对应城市数据
  if (props.mode === "city") {
    await loadCityData(province.code);
  }
};

/**
 * 选择城市
 * @param city 选中的城市
 */
const selectCity = (city: RegionData) => {
  selectedCity.value = city;
};

/**
 * 确认选择
 */
const handleConfirm = () => {
  if (!selectedProvince.value) {
    return;
  }

  if (props.mode === "city" && !selectedCity.value) {
    return;
  }

  const result: SelectionResult = {
    province: selectedProvince.value,
  };

  if (props.mode === "city" && selectedCity.value) {
    result.city = selectedCity.value;
  }

  // 设置确认标志位，避免触发cancel事件
  isConfirming.value = true;
  emit("confirm", result);
  emit("update:visible", false);
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  emit("update:visible", false);

  // 只有在不是确认操作时才发出cancel事件
  if (!isConfirming.value) {
    emit("cancel");
  }

  // 重置确认标志位
  isConfirming.value = false;
};

// 监听模式变化，重置选择状态
watch(
  () => props.mode,
  (newMode) => {
    if (newMode === "province") {
      selectedCity.value = null;
      cityList.value = [];
    }
  }
);

// 监听visible变化，初始化数据
watch(
  () => props.visible,
  async (newVisible) => {
    if (newVisible) {
      // 重置选择状态
      selectedProvince.value = null;
      selectedCity.value = null;
      cityList.value = [];

      // 初始化省份数据
      await initProvinceData();
    }
    setTimeout(() => {
      const tabbarPanel = document.querySelector(".taro-tabbar__panel");
      if (tabbarPanel) {
        if (newVisible) {
          tabbarPanel.classList.add("mask-region-picker");
        } else {
          tabbarPanel.classList.remove("mask-region-picker");
        }
      }
    }, 90);
  }
);

// 组件挂载时初始化
onMounted(async () => {
  await initProvinceData();
});
</script>
